﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BLL;
using DTO;

namespace GaraOto
{
    public partial class frmCustomerManager : DevExpress.XtraEditors.XtraUserControl
    {
        CustomerBLL customerBLL = new CustomerBLL();
        RegisterBLL registerBLL = new RegisterBLL();
        CardBLL cardBLL = new CardBLL();
        TypeBLL typeBLL = new TypeBLL();
        public frmCustomerManager()
        {
            InitializeComponent();
            BindingDataCustomer();
            ResetCustomer();
            tcbbSearchRegister.SelectedIndex = 0;
            tcbbSearchTypeCustomer.SelectedIndex = 0;
            BindingDataRegister();
            ResetRegister();
            FillDataComboboxType();
        }

        private void frmCustomerManager_Load(object sender, EventArgs e)
        {

        }

        public void BindingDataCustomer()
        {
            BindingSource bs = new BindingSource();
            bs.DataSource = customerBLL.SelectAll();
            bnvCustomer.BindingSource = bs;
            gcCustomers.DataSource = bs;

            btnEditCustomer.Enabled = false;
        }

        public void BindingDataRegister()
        {
            BindingSource bs = new BindingSource();
            bs.DataSource = registerBLL.SelectALL();
            bnvRegister.BindingSource = bs;
            gcRegisters.DataSource = bs;
        }

        public void FillDataComboboxType()
        {
            List<TypeDTO> list = typeBLL.FillDataCombobox();
            cbeTypeName.Properties.Items.Clear();
            for (int i = 0; i < list.Count; i++)
            {
                cbeTypeName.Properties.Items.Add(list[i].TypeName);
            }
            cbeTypeName.SelectedIndex = -1;

        }

        private void ResetCustomer()
        {
            teFirstName.Text = "";
            teLastName.Text = "";
            teAddress.Text = "";
            cbeSex.SelectedIndex = 0;
            deBirth.DateTime = DateTime.Now;
            teTel.Text = "";
            teEmail.Text = "";
            teCMND.Text = "";
            cbeStatus.SelectedIndex = 0;

            btnAddCustomer.Enabled = true;
            btnEditCustomer.Enabled = false;
        }

        private void ResetRegister()
        {
            teCustomerID.Text = "";
            teCardID.Enabled = true;
            teCardID.EditValue = null;
            deDateRegister.DateTime = DateTime.Now;
            deDateExpiration.DateTime = deDateRegister.DateTime.AddMonths(Convert.ToInt32(cbeMonth.SelectedItem));
            cbeTypeName.SelectedIndex = -1;
            cbeCardStatus.SelectedIndex = -1;
            cbeMonth.SelectedIndex = 0;
            teFeeRegister.Text = "";
            teName.Text = "";

            btnAddRegister.Enabled = true;
            btnExtension.Enabled = false;
        }


        private void btnAddCustomer_Click(object sender, EventArgs e)
        {
            CustomerDTO customerDTO = new CustomerDTO();
            customerDTO.FirstName = teFirstName.Text;
            customerDTO.LastName = teLastName.Text;
            customerDTO.Address = teAddress.Text;
            customerDTO.Sex = cbeSex.SelectedItem.ToString();
            customerDTO.DateOfBirth = deBirth.DateTime;
            customerDTO.Tel = teTel.Text;
            customerDTO.Email = teEmail.Text;
            customerDTO.CMND = teCMND.Text;
            customerDTO.Status = cbeStatus.SelectedItem.ToString();

            string message = customerBLL.Insert(customerDTO);
            if (message.Equals(MessageAction.Success))
            {
                MessageBox.Show("Thêm mới khách hàng thành công");
                BindingDataCustomer();
                ResetCustomer();
            }
            else
            {
                MessageBox.Show(message);
            }
        }

        private void btnEditCustomer_Click(object sender, EventArgs e)
        {
            CustomerDTO customerDTO = new CustomerDTO();
            int row = gvCustomers.GetSelectedRows()[0];
            customerDTO.CustomerID = gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcCustomerID).ToString();
            customerDTO.FirstName = teFirstName.Text;
            customerDTO.LastName = teLastName.Text;
            customerDTO.Address = teAddress.Text;
            customerDTO.Sex = cbeSex.SelectedItem.ToString();
            customerDTO.DateOfBirth = deBirth.DateTime;
            customerDTO.Tel = teTel.Text;
            customerDTO.Email = teEmail.Text;
            customerDTO.CMND = teCMND.Text;
            customerDTO.Status = cbeStatus.SelectedItem.ToString();

            string message = customerBLL.Update(customerDTO);
            if (message.Equals(MessageAction.Success))
            {
                MessageBox.Show("Cập nhật thông tin khách hàng thành công");
                BindingDataCustomer();
                ResetCustomer();
                gvCustomers.FocusedRowHandle = row;
            }
            else
            {
                MessageBox.Show(message);
            }
        }

        private void btnResetCustomer_Click(object sender, EventArgs e)
        {
            ResetCustomer();
        }

        private void gvCustomers_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            if (!registerBLL.CheckCustomerRegister(gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcCustomerID).ToString()))
            {
                ResetRegister();
            }
            else
            {
                    RegisterDTO registerDTO = registerBLL.LoadInfoCardOfCustomer(gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcCustomerID).ToString());
                    teCardID.Text = registerDTO.CardID;
            }
            teCustomerID.Text = gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcCustomerID).ToString();
            if (gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcName) != null)
            {
                teName.Text = gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcName).ToString();
                string[] name = gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcName).ToString().Split(' ');
                string firstname = name[name.Length - 1];
                string lastname = "";
                for (int i = 0; i < name.Length - 1; i++)
                {
                    lastname += name[i];
                    lastname += " ";
                }
                teFirstName.Text = firstname;
                teLastName.Text = lastname.Trim();
            }

            if (gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcAddress) != null)
                teAddress.Text = gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcAddress).ToString();
            if (gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcTel) != null)
            {
                teTel.Text = gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcTel).ToString();
            }
            cbeSex.SelectedItem = gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcSex);
            deBirth.EditValue = Convert.ToDateTime(gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcDateOfBirth));
            if (gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcEmail) != null)
                teEmail.Text = gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcEmail).ToString();
            if (gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcCMND) != null)
                teCMND.Text = gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcCMND).ToString();
            cbeStatus.SelectedItem = gvCustomers.GetRowCellValue(gvCustomers.GetSelectedRows()[0], gcStatus);

            btnAddCustomer.Enabled = false;
            btnEditCustomer.Enabled = true;
        }

        private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            gcCustomers.DataSource = customerBLL.SearchIDName(txtSearch.Text.Trim());
        }

        private void teCustomerID_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void btnAddRegister_Click(object sender, EventArgs e)
        {
            if (teCardID.Text != null)
            {
                if (cardBLL.CheckCardNotRegister(teCardID.Text.Trim()))
                {
                    if (teCustomerID.Text != "")
                    {
                        if (DateTime.Compare(deDateRegister.DateTime, deDateExpiration.DateTime) < 0)
                        {
                            RegisterDTO registerDTO = new RegisterDTO();
                            registerDTO.CustomerID = teCustomerID.Text;
                            registerDTO.CardID = teCardID.Text;
                            registerDTO.DateRegister = deDateRegister.DateTime;
                            registerDTO.DateExiration = deDateExpiration.DateTime;
                            registerDTO.Status = MessageAction.DangKy;
                            registerDTO.Fee = teFeeRegister.Text;
                            registerDTO.StaffID = "S007";

                            string message1 = registerBLL.Insert(registerDTO);
                            string message2 = cardBLL.UpdateCardStatus(teCardID.Text.Trim());
                            if (message1.Equals(MessageAction.Success) && message2.Equals(MessageAction.Success))
                            {
                                MessageBox.Show("Đăng ký thẻ gửi xe thành công");
                                BindingDataRegister();
                                ResetRegister();
                            }
                            else
                            {
                                MessageBox.Show("Đăng ký thẻ gửi xe không thành công");
                            }
                        }
                        else
                        {
                            MessageBox.Show("Ngày hết hạn phải muộn hơn ngày đăng ký");
                        }
                    }
                    else
                    {
                        MessageBox.Show("Bạn chưa chọn khách hàng cần đăng ký");
                    }
                }
                else
                {
                    MessageBox.Show("Thẻ không hợp lệ");
                }
            }
            else
            {
                MessageBox.Show("Bạn chưa quét thẻ");
            }
        }

        private void teCardID_Leave(object sender, EventArgs e)
        {
            if (teCardID.Text.Trim() != "")
            {
                if (!cardBLL.CheckCardIDExist(teCardID.Text.Trim()))
                {
                    teCardID.Text = "";
                    teFeeRegister.Text = "";
                    cbeCardStatus.SelectedIndex = -1;
                    cbeTypeName.SelectedIndex = -1;
                    teCardID.Focus();
                    MessageBox.Show("Thẻ không tồn tại");
                }
            }
        }

        private void teCardID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (teCardID.Text.Trim() != "")
                {
                    if (!cardBLL.CheckCardIDExist(teCardID.Text.Trim()))
                    {
                        teCardID.Text = "";
                        teFeeRegister.Text = "";
                        cbeCardStatus.SelectedIndex = -1;
                        cbeTypeName.SelectedIndex = -1;
                        teCardID.Focus();
                        MessageBox.Show("Thẻ không tồn tại");
                    }
                }
            }
        }

        private void gvRegisters_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            btnAddRegister.Enabled = false;
            teCardID.Enabled = false;
            if (gvRegisters.GetRowCellValue(gvRegisters.GetSelectedRows()[0], gcName) != null)
            {
                teName.Text = gvRegisters.GetRowCellValue(gvRegisters.GetSelectedRows()[0], gcName).ToString();
            }
            deDateRegister.DateTime = Convert.ToDateTime(gvRegisters.GetRowCellValue(gvRegisters.GetSelectedRows()[0], gcDateRegister));
            deDateRegister.Enabled = false;
            deDateExpiration.DateTime = Convert.ToDateTime(gvRegisters.GetRowCellValue(gvRegisters.GetSelectedRows()[0], gcDateExpiration));
            teFeeRegister.Text = gvRegisters.GetRowCellValue(gvRegisters.GetSelectedRows()[0], gcFee).ToString();
            teCustomerID.Text = gvRegisters.GetRowCellValue(gvRegisters.GetSelectedRows()[0], gcRegisterCustomerID).ToString();
                teCardID.Text = "";
                teCardID.Text = gvRegisters.GetRowCellValue(gvRegisters.GetSelectedRows()[0], gcCardID).ToString();
            cbeTypeName.SelectedItem = gvRegisters.GetRowCellValue(gvRegisters.GetSelectedRows()[0], gcTypeName);
            cbeCardStatus.SelectedItem = gvRegisters.GetRowCellValue(gvRegisters.GetSelectedRows()[0], gcCardStatus);

        }


        private void btnResetRegister_Click(object sender, EventArgs e)
        {
            ResetRegister();
        }

        private void cbeMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            deDateExpiration.DateTime = deDateRegister.DateTime.AddMonths(Convert.ToInt32(cbeMonth.SelectedItem));
            if (teCardID.Text.Trim() != "")
            {
                if (cardBLL.CheckCardNotRegister(teCardID.Text.Trim()))
                {
                    CardDTO cardDTO = cardBLL.LoadInfoCard(teCardID.Text.Trim());
                    int feeRegister = Convert.ToInt32(System.Text.RegularExpressions.Regex.Replace(cardDTO.FeeRegister, @"\s+", ""));
                    int feeExtension = Convert.ToInt32(System.Text.RegularExpressions.Regex.Replace(cardDTO.FeeExtension, @"\s+", ""));
                    teFeeRegister.Text = MessageAction.FormatMoney((feeRegister + feeExtension * Convert.ToInt32(cbeMonth.SelectedItem)).ToString());
                }
            }
        }

        private int getRowCustomerID(string customerID)
        {
            for (int i = 0; i < gvCustomers.RowCount; i++)
            {
                if (gvCustomers.GetRowCellValue(i, gcCustomerID).ToString().Equals(customerID))
                {
                    return i;
                }
            }
            return -1;
        }

        private int getRowRegisterID(string registerID)
        {
            for (int i = 0; i < gvRegisters.RowCount; i++)
            {
                if (gvRegisters.GetRowCellValue(i, gcRegisterID).ToString().Equals(registerID))
                {
                    return i;
                }
            }
            return -1;
        }

        private void teCardID_TextChanged(object sender, EventArgs e)
        {
            if (cardBLL.CheckCardNotRegister(teCardID.Text.Trim()))
            {
                CardDTO cardDTO = cardBLL.LoadInfoCard(teCardID.Text.Trim());
                int feeRegister = Convert.ToInt32(System.Text.RegularExpressions.Regex.Replace(cardDTO.FeeRegister, @"\s+", ""));
                int feeExtension = Convert.ToInt32(System.Text.RegularExpressions.Regex.Replace(cardDTO.FeeExtension, @"\s+", ""));
                teFeeRegister.Text = MessageAction.FormatMoney((feeRegister + feeExtension * Convert.ToInt32(cbeMonth.SelectedItem)).ToString());
                cbeCardStatus.SelectedItem = cardDTO.Status;
                cbeTypeName.SelectedItem = cardDTO.TypeName;
            }
            if (cardBLL.CheckCardTheLuot(teCardID.Text.Trim()) && !teCardID.Text.Equals(""))
            {
                teFeeRegister.Text = "";
                cbeCardStatus.SelectedIndex = -1;
                cbeTypeName.SelectedIndex = -1;
                MessageBox.Show("Thẻ không hợp lệ");
            }

            if (cardBLL.CheckCardRegister(teCardID.Text.Trim()))
            {
                btnExtension.Enabled = false;
                btnAddRegister.Enabled = false;
                CardDTO cardDTO = cardBLL.LoadInfoCard(teCardID.Text.Trim());
                cbeCardStatus.SelectedItem = cardDTO.Status;
                cbeTypeName.SelectedItem = cardDTO.TypeName;
                int feeRegister = Convert.ToInt32(System.Text.RegularExpressions.Regex.Replace(cardDTO.FeeRegister, @"\s+", ""));
                int feeExtension = Convert.ToInt32(System.Text.RegularExpressions.Regex.Replace(cardDTO.FeeExtension, @"\s+", ""));
                teFeeRegister.Text = MessageAction.FormatMoney((feeRegister + feeExtension * Convert.ToInt32(cbeMonth.SelectedItem)).ToString());
                RegisterDTO registerDTO = registerBLL.LoadInfoRegister(teCardID.Text.Trim());
                teCustomerID.Text = registerDTO.CustomerID;
                teName.Text = registerDTO.Name;
                if (cardDTO.Status.Equals("Hết hạn"))
                {
                    DialogResult result2 = MessageBox.Show("Thẻ đã hết hạn. Bạn muốn gia hạn ko?",
"Gia hạn thẻ",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question);
                    if (result2 == DialogResult.Yes)
                    {
                        btnExtension.Enabled = true;
                        deDateRegister.DateTime = DateTime.Now;
                        deDateExpiration.DateTime = deDateRegister.DateTime.AddMonths(Convert.ToInt32(cbeMonth.SelectedItem));
                    }
                }
                else
                    if (cardDTO.Status.Equals("Sử dụng"))
                    {
                        DialogResult result2 = MessageBox.Show("Bạn muốn gia hạn thêm cho thẻ?",
    "Gia hạn thẻ",
    MessageBoxButtons.YesNoCancel,
    MessageBoxIcon.Question);
                        if (result2 == DialogResult.Yes)
                        {
                            btnExtension.Enabled = true;
                            deDateRegister.DateTime = registerDTO.DateExiration;
                            deDateExpiration.DateTime = deDateRegister.DateTime.AddMonths(Convert.ToInt32(cbeMonth.SelectedItem));
                        }
                    }

                if (getRowCustomerID(teCustomerID.Text) != -1)
                {
                    gvCustomers.FocusedRowHandle = getRowCustomerID(teCustomerID.Text);
                }
            }
        }


        private void btnExtension_Click(object sender, EventArgs e)
        {
            if (teCustomerID.Text != "")
            {
                RegisterDTO registerDTO = new RegisterDTO();
                registerDTO.CustomerID = teCustomerID.Text;
                registerDTO.CardID = teCardID.Text;
                registerDTO.DateRegister = deDateRegister.DateTime;
                registerDTO.DateExiration = deDateExpiration.DateTime;
                registerDTO.Fee = teFeeRegister.Text;
                registerDTO.Status = MessageAction.GiaHan;
                registerDTO.StaffID = "S007";

                string message = registerBLL.Insert(registerDTO);
                string message2 = cardBLL.UpdateCardStatusExtension(teCardID.Text.Trim());
                if (message.Equals(MessageAction.Success) && message2.Equals(MessageAction.Success))
                {
                    MessageBox.Show("Gia hạn thẻ gửi xe thành công");
                    BindingDataRegister();
                    ResetRegister();
                }
                else
                {
                    MessageBox.Show("Gia hạn thẻ gửi xe không thành công");
                }
            }
            else
            {
                MessageBox.Show("Thẻ chưa đăng ký cho khách hàng nào");
            }
        }

    }
}
